import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86136
 * Date: 2025-05-05
 * Time: 13:11
 */
public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient(String serverIp, int port) throws IOException {
        socket = new Socket(serverIp,port);
    }
    public void start () {
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            //为了方便，套壳操作
            Scanner scannerNet = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            //从控制台读取请求，发送给服务器
            while(true) {
                if(!scanner.hasNext()) {//判断收到的数据中是否包含"空白符"(换行、回车、制表符、翻页符...)
                    break;
                }
                //1.从控制台读取用户输入信息
                String request = scanner.next();

                //2.发送给服务器
                //这个操作只是把数据放到“发送缓冲区"，并没有真正写入网卡
                //暗暗约定一个请求/响应使用\n作为结束标记
                writer.println(request);
                //flush方法用来“冲刷缓冲区”
                writer.flush();
                //使用PrintWriter的行为，不进行套壳就可以直接发送

                //3.读取服务器返回的响应
                String response = scannerNet.next();

                //4.将返回的响应进行打印
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
